//============================ Tools ====================================
let Tools = {
  // 获取两个数之间的随机整数
  getRandom (min,max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; 
  },
  // 获取随机颜色
  getRandomColor () {
    let r = this.getRandom(0,255);
    let g = this.getRandom(0,255);
    let b = this.getRandom(0,255);
    return "rgb("+r+","+g+","+b+")";
  }
}

//============================ Food ====================================
class Food {
  constructor(options) {
    options = options instanceof Object ? options : {};
    this.x = options.x || 0;
    this.y = options.y || 0;
    this.width = options.width || 20;
    this.height = options.height || 20;
    this.color = options.color || "green";
    this.elements = [];
  }
  // 定义一个将食物渲染到页面上的方法
  render(map) {
    let ele = document.createElement("div");
    // 随机获取x、y的坐标
    this.x = Tools.getRandom(0, map.clientWidth / this.width - 1) * this.width;
    this.y = Tools.getRandom(0, map.clientHeight / this.height - 1) * this.height;
    // 给元素添加样式属性
    ele.style.width = this.width + "px";
    ele.style.height = this.height + "px";
    ele.style.left = this.x + "px";
    ele.style.top = this.y + "px";
    ele.style.position = "absolute";
    ele.style.backgroundColor = this.color;
    map.appendChild(ele);
    this.elements.push(ele);
  }
  // 定义一个删除食物的方法
  remove (map,i) {
    map.removeChild(this.elements[i]);
    this.elements.splice(i,1);
  }
}

//============================ Snake ====================================
class Snake {
  constructor(options) {
    options = options instanceof Object ? options : {};
    this.width = options.width || 20;
    this.height = options.height || 20;
    // 蛇头和身体，第一个位置表示蛇头
    this.body = [
      {x:3,y:2,color:"red"},
      {x:2,y:2,color:"skyblue"},
      {x:1,y:2,color:"skyblue"}
    ];
    this.direction = "right";
    this.elements = [];
  }
  // 定义一个将蛇渲染到页面上的方法
  render (map) {
    for(let i = 0; i < this.body.length; i++) {
      let ele = document.createElement("div");
      ele.style.width = this.width + "px";
      ele.style.height = this.height + "px";
      ele.style.backgroundColor = this.body[i].color;
      ele.style.left = this.body[i].x * this.width + "px";
      ele.style.top = this.body[i].y * this.height + "px";
      ele.style.position = "absolute";
      map.appendChild(ele);
      this.elements.push(ele);
    }
  }
  // 定义一个让蛇运动的方法
  move () {
    for(let i = this.body.length-1; i > 0; i--) {
      this.body[i].x = this.body[i-1].x;
      this.body[i].y = this.body[i-1].y;
    }
    // 蛇头位置变化根据按键的方向变化
    let head = this.body[0];
    switch(this.direction) {
      case "right":
        head.x += 1;
        break;
      case "left":
        head.x -= 1;
        break;
      case "top":
        head.y -= 1;
        break;
      case "bottom":
        head.y += 1;
        break;
    } 
  }
  // 定义一个删除蛇的方法
  remove (map) {
    for (let i = this.elements.length-1; i >= 0; i--) {
      map.removeChild(this.elements[i]);
    }
    this.elements = [];
  }
}

//============================ Game ====================================
class Game {
  constructor(){
    this.food = new Food();
    this.snake = new Snake();
    this.map = document.getElementById("map");
  }
  start () {
    // 将食物和蛇渲染到页面上
    this.food.render(this.map);
    this.food.render(this.map);
    this.food.render(this.map);
    this.snake.render(this.map);
    this.runSnake();
    this.bindKey();
  }
  // 蛇持续运动的方法
  runSnake () {
    let timer = setInterval(() => {
      this.snake.remove(this.map);
      this.snake.move();
      this.snake.render(this.map);
      // 触碰地图四周游戏结束
      let maxX = this.map.clientWidth / this.snake.width;
      let maxY = this.map.clientHeight / this.snake.height;
      let headX = this.snake.body[0].x;
      let headY = this.snake.body[0].y;
      if (headX < 0 || headX >= maxX || headY < 0 || headY >= maxY) {
        clearInterval(timer);
        alert("Game over");
      }
      // 判断是否吃到食物，吃到则蛇节增加一节，该食物移除，重新渲染一个新的食物
      let hX = headX * this.snake.width;
      let hY = headY * this.snake.height;
      // if(hX === this.food.x && hY === this.food.y) {
      //   let last = this.snake.body[this.snake.body.length-1];
      //   this.snake.body.push({x:last.x, y:last.y, color:last.color});
      //   this.food.remove(this.map,0);
      //   this.food.render(this.map);
      // }
      for(let i = 0; i < this.food.elements.length; i++) {
        if(hX === this.food.elements[i].offsetLeft && hY === this.food.elements[i].offsetTop) {
          console.log(this.food.elements[i])
          this.food.remove(this.map,i);
          this.food.render(this.map);
          let last = this.snake.body[this.snake.body.length-1];
          this.snake.body.push({x:last.x, y:last.y, color:last.color});
        }
      }
    },100);
  }
  // 按键控制蛇移动方向
  bindKey () {
    document.onkeydown = (e) => {
      // console.log(e.keyCode);
      //上：38；下：40；左：37；右：39
      switch(e.keyCode) {
        case 37:
          this.snake.direction = "left";
          break;
        case 38:
          this.snake.direction = "top";
          break;
        case 39:
          this.snake.direction = "right";
          break;
        case 40:
          this.snake.direction = "bottom";
          break;
      }
    }
  }
}

//============================ main ====================================
let game = new Game();
game.start();